﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kaixin.BLL.Helper;
using System.Collections;
using System.Text.RegularExpressions;
using Kaixin.BLL.Model;

namespace Kaixin.BLL
{
    /// <summary>
    /// 用于获取用户UID以及好友UID
    /// </summary>
    public class UserID
    {
        //用户登陆后的UID
        public string MyUID { get; set; }
        /// <summary>
        /// 获取用户ID，意味着用户必须登录成功后方可获取
        /// </summary>
        public string GetUid(string email,string pwd)
        {

            string val = RegexHelper.Match(WebHelper.Post("http://www.kaixin001.com/login/login.php",
                                                          string.Format("email={0}&password={1}", email, pwd)),
                                           RegexHelper.AllFirendAReg);
            MyUID = RegexHelper.Match(val, RegexHelper.NumberReg);
            return MyUID;
        }
        /// <summary>
        /// 获取我的好友UID
        /// </summary>
        public List<User> GetFriendsList()
        {
            return GetFriendsList(MyUID);
        }
        /// <summary>
        /// 获取好友的好友UID包括好友自己本身
        /// </summary>
        public List<User> GetFriendsList(string uid)
        {
            int limit = uid == MyUID ? 40 : 20;
            string html = WebHelper.Get("http://www.kaixin001.com/friend/?uid=" + uid);
            int max = 0;
            foreach (GroupCollection item in RegexHelper.Matches(html, RegexHelper.FirendMaxStartReg))
            {
                max = max > int.Parse(item[1].Value) ? max : int.Parse(item[1].Value);
            }
            List<DictionaryEntry> list = RegexHelper.MatchToUidAndName(html, RegexHelper.FirendAReg);//第一页好友列表
            if (max != 0)
            {
                int start = limit;
                while (max >= start)
                {
                    html = WebHelper.Get(string.Format("http://www.kaixin001.com/friend/?uid={0}&viewtype=&start={1}", uid, start));
                    list.AddRange(RegexHelper.MatchToUidAndName(html, RegexHelper.FirendAReg));
                    start += limit;
                }
            }
            List<User> ret = new List<User>();
            foreach (var dictionaryEntry in list.Distinct().ToList())
            {
                ret.Add(new User {UID = dictionaryEntry.Key.ToString(), Name = dictionaryEntry.Value.ToString()});
            }
            return ret;
        }
    }
}
